package craky.keeper.user;

import java.io.Serializable;

import craky.security.Digest;

public class User implements Serializable {
	private static final long serialVersionUID = -1818298155807080501L;
	public static final int ADMIN = 0;
	public static final int USER = 10;
	public static final int VISITOR = 20;
	public static final int MIN_PASSWORD_LENGTH = 4;
	public static final int MAX_PASSWORD_LENGTH = 100;
	public static final String ADMIN_DES = "超级管理员";
	public static final String USER_DES = "一般用户";
	public static final String VISITOR_DES = "受限参观者";
	public static final String USER_NOT_EXIST = "该用户不存在！";
	public static final String USER_ALREADY_EXIST = "该用户已存在！";
	public static final String ILLEGAL_PASSWORD = "密码错误！";
	public static final String NAME_UNALLOWED = "非法用户名！";
	public static final String PASSWORD_LENGTH_ERROR = "密码长度不能小于4位！";
	public static final String NAME_REGEX_INFO = "用户名不能为空且不能出现半角逗号(,)！";
	private int id;
	private String name;
	private String password;
	private int purview;
	private boolean autoLogin;
	private boolean savePassword;

	public int getId() {
		return this.id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getPurview() {
		return this.purview;
	}

	public void setPurview(int purview) {
		this.purview = purview;
	}

	public boolean isAutoLogin() {
		return this.autoLogin;
	}

	public void setAutoLogin(boolean autoLogin) {
		this.autoLogin = autoLogin;
	}

	public boolean isSavePassword() {
		return this.savePassword;
	}

	public void setSavePassword(boolean savePassword) {
		this.savePassword = savePassword;
	}

	public String getPurviewName() {
		String pn = null;

		switch (this.purview) {
		case 0:
			pn = "超级管理员";
			break;
		case 10:
			pn = "一般用户";
			break;
		case 20:
			pn = "受限参观者";
		}

		return pn == null ? "" : pn;
	}

	public void setPurviewName(String purviewName) {
		setPurview(getPurviewByName(purviewName));
	}

	@Override
	public String toString() {
		return this.name + ", purview=" + this.purview;
	}

	public static int getPurviewByName(String name) {
		if (name.equals("超级管理员")) {
			return 0;
		}
		if (name.equals("一般用户")) {
			return 10;
		}

		return 20;
	}

	public static String createCiphertext(String name, String password) {
		return Digest.computeMD5(Digest.computeMD5(name)
				+ Digest.computeMD5(password));
	}

	public static boolean isAllowedName(String name) {
		return (name != null) && (!(name = name.trim()).isEmpty())
				&& (name.indexOf(',') < 0);
	}

	public static boolean isAllowedPassword(String password) {
		return password.length() >= 4;
	}
}